package com.a3dweijing.wetouch2.Activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.a3dweijing.wetouch2.Common.CallBack;
import com.a3dweijing.wetouch2.R;
import com.a3dweijing.wetouch2.Util.AlerDialogHelp;
import com.a3dweijing.wetouch2.Util.ProgressDialogHelp;
import com.a3dweijing.wetouch2.network.RetrofitUtil;
import com.a3dweijing.wetouch2.Util.Util;
import com.a3dweijing.wetouch2.adapter.GoodsByOrderAdapter;
import com.a3dweijing.wetouch2.base.BaseActivity;
import com.a3dweijing.wetouch2.bean.GoodsInfoBean;
import com.a3dweijing.wetouch2.bean.GoodsListBean;
import com.a3dweijing.wetouch2.bean.OrderListBean;
import com.a3dweijing.wetouch2.bean.PendingPaymentMsg;
import com.a3dweijing.wetouch2.bean.ResultMsg;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static com.a3dweijing.wetouch2.Activity.BuyActivity.BUYACTIVITYCODE;
import static com.a3dweijing.wetouch2.Activity.RefundActivity.REFUNDACTIVITYCODE;

public class OrderItemActivity extends BaseActivity
{
    
    @BindView(R.id.top_text)
    TextView topText;
    
    @BindView(R.id.top_right)
    TextView topRight;
    
    @BindView(R.id.top_all)
    RelativeLayout topAll;
    
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    
    @BindView(R.id.loading_date)
    LinearLayout loadingDate;
    
    @BindView(R.id.resaut_status_img)
    ImageView resautStatusImg;
    
    @BindView(R.id.resaut_status)
    LinearLayout resautStatus;
    
    @BindView(R.id.listview)
    RecyclerView listview;
    
    @BindView(R.id.all_money)
    TextView allMoney;
    
    @BindView(R.id.refund)
    RelativeLayout refund;
    
    @BindView(R.id.delivergoods)
    RelativeLayout delivergoods;
    
    @BindView(R.id.look_logistics)
    RelativeLayout lookLogistics;
    
    @BindView(R.id.confirm)
    RelativeLayout confirm;
    
    @BindView(R.id.cancel_order)
    RelativeLayout cancelOrder;
    
    @BindView(R.id.pay)
    RelativeLayout pay;
    
    @BindView(R.id.back)
    ImageView back;
    
    private ArrayList<GoodsListBean> list;
    
    private OrderListBean item;
    
    private GoodsByOrderAdapter adapter;
    
    private AlertDialog dialog;
    
    private AlertDialog dialogQury;
    
    private ProgressDialog progressDialog;
    
    public static int ORDERITEMACTIVITYCODE = 124;
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_item);
        ButterKnife.bind(this);
        item = (OrderListBean)getIntent().getSerializableExtra("item");
        if (item == null)
            return;
        initView();
        initDate();
        setButton();
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == BUYACTIVITYCODE && resultCode == RESULT_OK)
        {
            OrderItemActivity.this.setResult(RESULT_OK);
            finish();
        }
        else if (requestCode == REFUNDACTIVITYCODE && resultCode == RESULT_OK)
        {
            OrderItemActivity.this.setResult(RESULT_OK);
            finish();
        }
    }
    
    private void setButton()
    {
        allMoney.setText("￥:" + item.getOrder_total() + "");
        switch (item.getOrder_state())
        {
            case 1:
                cancelOrder.setVisibility(View.VISIBLE);
                setTextButton(cancelOrder);
                pay.setVisibility(View.VISIBLE);
                setTextButton(pay);
                break;
            case 2:
                delivergoods.setVisibility(View.VISIBLE);
                setTextButton(delivergoods);
                
                break;
            case 3:
                lookLogistics.setVisibility(View.VISIBLE);
                setTextButton(lookLogistics);
                confirm.setVisibility(View.VISIBLE);
                setTextButton(confirm);
                break;
            case 4:
            case 5:
                refund.setVisibility(View.VISIBLE);
                setTextButton(refund);
                break;
            
        }
    }
    
    private void setTextButton(View view)
    {
        TextView viewById = view.findViewById(R.id.infotv);
        viewById.setText(PendingPaymentMsg.getOperableName(view.getId()));
    }
    
    private void initDate()
    {
        loadingDate.setVisibility(View.VISIBLE);
        resautStatus.setVisibility(View.GONE);
        final Observable<GoodsOrOrderItem> getordergoods =
            RetrofitUtil.getInstance().getApiOfPhp().getordergoods(item.getOrder_id());
        getordergoods.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(
            new Observer<GoodsOrOrderItem>()
            {
                @Override
                public void onSubscribe(Disposable d)
                {
                    disposables.add(d);
                }
                
                @Override
                public void onNext(GoodsOrOrderItem goodsOrOrderItem)
                {
                    if (goodsOrOrderItem.isFlag() && goodsOrOrderItem.getGoodsList() != null
                        && goodsOrOrderItem.getGoodsList().size() > 0)
                    {
                        list.clear();
                        list.addAll(goodsOrOrderItem.getGoodsList());
                        adapter.notifyDataSetChanged();
                    }
                    else
                        resautStatus.setVisibility(View.VISIBLE);
                }
                
                @Override
                public void onError(Throwable e)
                {
                    loadingDate.setVisibility(View.GONE);
                    resautStatus.setVisibility(View.VISIBLE);
                }
                
                @Override
                public void onComplete()
                {
                    loadingDate.setVisibility(View.GONE);
                }
            });
    }
    
    /**
     * 确认收货的订单
     */
    
    CallBack callBackQary = new CallBack()
    {
        @Override
        public void doNext(int what, Object obj)
        {
            quryOrder();
        }
    };
    
    /**
     * 取消订单的回调
     */
    CallBack callBack = new CallBack()
    {
        @Override
        public void doNext(int what, Object obj)
        {
            cancelOrder();
        }
    };
    
    private void quryOrder()
    {
        progressDialog.show();
        Observable<ResultMsg> observable = RetrofitUtil.getInstance().getApiOfPhp().receiptGood(item.getOrder_id());
        observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(
            new Observer<ResultMsg>()
            {
                @Override
                public void onSubscribe(Disposable d)
                {
                    disposables.add(d);
                }
                
                @Override
                public void onNext(ResultMsg resultMsg)
                {
                    if (resultMsg != null && resultMsg.isFlag())
                    {
                        OrderItemActivity.this.setResult(RESULT_OK);
                        finish();
                    }
                    else
                        Toast.makeText(OrderItemActivity.this, "确认失败", Toast.LENGTH_SHORT).show();
                }
                
                @Override
                public void onError(Throwable e)
                {
                    progressDialog.dismiss();
                }
                
                @Override
                public void onComplete()
                {
                    progressDialog.dismiss();
                }
            });
    }
    
    private void cancelOrder()
    {
        progressDialog.show();
        Observable<ResultMsg> observable = RetrofitUtil.getInstance().getApiOfPhp().cancelOrder(item.getOrder_id());
        observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(
            new Observer<ResultMsg>()
            {
                @Override
                public void onSubscribe(Disposable d)
                {
                    disposables.add(d);
                }
                
                @Override
                public void onNext(ResultMsg resultMsg)
                {
                    if (resultMsg != null && resultMsg.isFlag())
                    {
                        OrderItemActivity.this.setResult(RESULT_OK);
                        finish();
                    }
                    else
                        Toast.makeText(OrderItemActivity.this, "删除失败", Toast.LENGTH_SHORT).show();
                }
                
                @Override
                public void onError(Throwable e)
                {
                    progressDialog.dismiss();
                }
                
                @Override
                public void onComplete()
                {
                    progressDialog.dismiss();
                }
            });
    }
    
    private void initView()
    {
        dialog = AlerDialogHelp.create(this, "提示", "您确定要取消订单吗", true, callBack);
        dialogQury = AlerDialogHelp.create(this, "提示", "您确定改变订单状态吗", true, callBackQary);
        progressDialog = ProgressDialogHelp.create(this, "提示", "删除中", false);
        topText.setText("订单详情");
        list = new ArrayList<>();
        adapter = new GoodsByOrderAdapter(this, list);
        adapter.setOrderListBean(item);
        listview.setLayoutManager(new LinearLayoutManager(this));
        listview.setAdapter(adapter);
    }
    
    public static void startActivity(Activity activity, OrderListBean orderListBean)
    {
        if (Util.isFastClick())
        {
            Intent intent = new Intent(activity, OrderItemActivity.class);
            intent.putExtra("item", orderListBean);
            activity.startActivityForResult(intent, ORDERITEMACTIVITYCODE);
        }
        
    }
    
    @OnClick({R.id.refund, R.id.delivergoods, R.id.look_logistics, R.id.confirm, R.id.cancel_order, R.id.pay,
        R.id.back})
    public void onViewClicked(View view)
    {
        switch (view.getId())
        {
            case R.id.back:
                finish();
                break;
            case R.id.refund:
                RefundActivity.startActivity(OrderItemActivity.this, item);
                break;
            case R.id.delivergoods:
                break;
            case R.id.look_logistics:
                MarKetActivity.startActivity(OrderItemActivity.this, item.getOrder_id());
                break;
            case R.id.confirm:
                dialogQury.show();
                break;
            case R.id.cancel_order:
                dialog.show();
                break;
            case R.id.pay:
                tobePay();
                break;
        }
    }
    
    private void tobePay()
    {
        ArrayList<GoodsInfoBean> goodsInfoBeans = new ArrayList<>();
        for (GoodsListBean goodsListBean : list)
        {
            GoodsInfoBean goodsInfoBean = new GoodsInfoBean();
            goodsInfoBean.setNumber(goodsListBean.getGoods_number());
            goodsInfoBean.setS_goods_img_url_long(goodsListBean.getGoods_imgurl());
            goodsInfoBean.setS_goods_img_url(goodsListBean.getGoods_imgurl());
            goodsInfoBean.setS_price(goodsListBean.getGoods_money());
            goodsInfoBean.setS_goods_name(goodsListBean.getGoods_name());
            goodsInfoBean.setS_goods_id(goodsListBean.getGoods_id());
            goodsInfoBean.setNumber(goodsListBean.getGoods_number());
            goodsInfoBeans.add(goodsInfoBean);
        }
        BuyActivity.startActivity(this, goodsInfoBeans);
    }
}
